#!/usr/bin/env python

import random
from math import factorial

class node(object):
	def __init__(self):
		self.has_packet = False
	
	def receive_packet(self, succesrate):
		if random.random() <= succesrate:
			self.has_packet = True
			
	def reset(self):
		self.has_packet = False


def uc_probability_after_transmissions(unique_packets, total_transmissions, succesrate, node_count):
	if unique_packets > total_transmissions:
		return 0
	else:
		return (1-((1-succesrate)**(float(total_transmissions)/float(unique_packets*node_count))))**unique_packets
	
		

if __name__=='__main__':

	### Setup HERE!!: ###

	node_count = 10
	succesrate = 0.6
	transmissions = 4

	### /Setup ###


	sample_space = 0
	node_rate = succesrate
	print '\nCalculations:'
	for i in range(transmissions):
		node_rate = sample_space*succesrate+node_rate
		print 'Probability of succes after',i+1,'transmission(s):', node_rate**node_count
		sample_space = 1-node_rate

	print
	print 'TEST:Probability of succes after',1,'transmission(s):', bc_probability_after_transmissions(1,1,succesrate)**node_count
	print 'TEST:Probability of succes after',2,'transmission(s):', bc_probability_after_transmissions(1,2,succesrate)**node_count
	print 'TEST:Probability of succes after',3,'transmission(s):', bc_probability_after_transmissions(1,3,succesrate)**node_count
	print 'TEST:Probability of succes after',4,'transmission(s):', bc_probability_after_transmissions(1,4,succesrate)**node_count


	nodes = []
	reps = 10000
	print
	print 'Starting simulation with stats:'
	print 'devices =',node_count
	print 'succesrate =',succesrate
	print 'transmissions =',transmissions
	print 'reps =',reps


	fail = [0 for i in range(transmissions)]

	print '\nSimulation running..'

	for i in range(node_count):
		nodes.append(node())
	
	for i in range(reps):
		for j in range(transmissions):
			for node in nodes:
				node.receive_packet(succesrate)
	
			for node in nodes:
				if not node.has_packet:
					fail[j] = fail[j] + 1
					break
			
		for node in nodes:
			node.reset()
		
	for k in range(len(fail)):		
		print 'fails in transmission',k+1,':',fail[k],'out of',reps,'reps. Succes:',(reps-fail[k])/float(reps)
	
		
	
